package indi.lddsdu.spider.dao;

import java.util.List;
import java.util.ArrayList;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import us.codecraft.webmagic.Request;
import indi.lddsdu.spider.bean.UnDownloadUrl;

/**
 * Created by jack on 18/6/6.
 */

@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class UnDownloadUrlDao {
    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession(){
        try {
            return sessionFactory.getCurrentSession();
        }catch (Exception e){
            System.out.println(e);
        }
        return null;
    }

    public void addUnDownloadUrl(UnDownloadUrl unDownloadUrl){
        getSession().save(unDownloadUrl);
    }

    /**
     * 查询所有的添加进数据库的url
     * @return
     */
    public List<Request> findAllUndownloadUrl(){
        String hql = "from UnDownloadUrl as unDownloadUrl";
        Query query =  getSession().createQuery(hql);
        List<Request> requests = new ArrayList<Request>();
        List<UnDownloadUrl> unDownloadUrls = query.list();
        for (UnDownloadUrl unDownloadUrl : unDownloadUrls){
            requests.add(new Request(unDownloadUrl.getUrl()));
        }
        //删除
        return requests;
    }

    /**
     * 在查询过后删除库中所有的东西
     * TODO
     */
    public void deleteAll() throws Exception {
        String hql = "delete from " + UnDownloadUrl.class.getName();
        Query query = getSession().createQuery(hql);
        try {
            query.executeUpdate();
        }catch (HibernateException e){
            throw new Exception(String.format("Error occured when exec hql : %s", hql));
        }
    }
}
